package handlers

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"user-login-sys/models"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.Video{}).Count(&count)

	var video []models.Video
	err := models.DB.Offset(offset).Limit(size).Find(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "列表展示失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "列表展示成功",
			"data": gin.H{
				"count": count,
				"data":  video,
			},
		})
		return
	}

}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	des := c.PostForm("des")

	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Video{

		Title:   title,
		Content: content,
		Des:     des,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "数据添加成功",
		})
		return
	}

}
